using System;
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.SharePoint.Security;
using System.Web;
using System.Security.Permissions;
using System.Threading;

namespace BAS.Dovas.WebControls
{

    public class DateTimeSecFieldControl : BaseFieldControl
    {

        #region Controls
        protected DropDownList DropDownHH;
        protected DropDownList DropDownMM;
        protected DropDownList DropDownSS;
        protected DateTimeControl TheDatePicker;
        protected Label LabelDate;
        #endregion

        #region DefaultTemplateName
        /// <summary>
        /// Getting Default Template Name
        /// </summary>
        protected override string DefaultTemplateName
        {
            [SharePointPermission(
                 SecurityAction.LinkDemand, ObjectModel = true)]
            [AspNetHostingPermission(SecurityAction.LinkDemand,
                    Level = AspNetHostingPermissionLevel.Minimal)]
            get { return "DateTimeSecField"; }
        }
        #endregion

        #region Value
        /// <summary>
        /// Setting and Getting the Field Control Value
        /// Use Different format in New Form and Display form
        /// New and Edit form Format : HH AM MM
        /// Dispay form Format : HH : MM AM
        /// Get the selected date from the date time picker and concatenate the time value to the end
        /// </summary>
        public override object Value
        {
            [SharePointPermission(
                  SecurityAction.LinkDemand, ObjectModel = true)]
            [AspNetHostingPermission(SecurityAction.LinkDemand,
                    Level = AspNetHostingPermissionLevel.Minimal)]
            get
            {
                SPTimeZone sptimeZone = ItemContext.RegionalSettings.TimeZone;
                EnsureChildControls();
                string theDate = TheDatePicker.SelectedDate.ToLocalTime().Date.ToShortDateString();
                //string hhString = DropDownHH.Text.Trim();
                string fieldValue = string.Empty;
                //string hhValue = string.Empty;
                //string mValue = string.Empty;
                //if (hhString.Length == 4)
                //{
                //    hhValue = hhString.Substring(0, 1);
                //    mValue = hhString.Substring(1);

                //}
                //else if (hhString.Length == 5)
                //{
                //    hhValue = hhString.Substring(0, 2);
                //    mValue = hhString.Substring(2);
                //}
                fieldValue = theDate + " " + DropDownHH.Text.Trim() + ":" + DropDownMM.Text.Trim() + ":" + DropDownSS.Text.Trim();
                return System.DateTime.Parse(fieldValue);
                //DateTime dateTime = System.DateTime.Parse(fieldValue);
                //return sptimeZone.UTCToLocalTime(dateTime);
                 
            }
        
            [SharePointPermission(
                   SecurityAction.LinkDemand, ObjectModel = true)]
            [AspNetHostingPermission(SecurityAction.LinkDemand,
                    Level = AspNetHostingPermissionLevel.Minimal)]
            set
            {
                SPTimeZone sptimeZone = ItemContext.RegionalSettings.TimeZone;
                EnsureChildControls();

                //DateTime dateTime = sptimeZone.LocalTimeToUTC(System.DateTime.Parse(value.ToString()));

                //string fieldValue = dateTime.ToString();
                string fieldValue = value.ToString();

                if (this.ControlMode == SPControlMode.Display)
                    LabelDate.Text = fieldValue;
                else
                {

                    string currentHH = fieldValue.Substring(fieldValue.IndexOf(' ') + 1, (fieldValue.IndexOf(':') - (fieldValue.IndexOf(' ') + 1)));
                    string currentMM = fieldValue.Substring(fieldValue.IndexOf(':') + 1, 2);
                    string currentSS = fieldValue.Substring(fieldValue.IndexOf(':') + 4, 2);
                    DropDownHH.Text = currentHH; // +" " + currentM;
                    DropDownMM.Text = currentMM;
                    DropDownSS.Text = currentSS;

                    TheDatePicker.SelectedDate = System.DateTime.Parse(fieldValue.Substring(0, fieldValue.IndexOf(' ')));
                    //System.DateTime.Parse(dateTime.ToShortDateString()); //
                }
            }
        }
        #endregion

        #region Focus
        [SharePointPermission(
                SecurityAction.LinkDemand, ObjectModel = true)]
        [AspNetHostingPermission(SecurityAction.LinkDemand,
                   Level = AspNetHostingPermissionLevel.Minimal)]
        public override void Focus()
        {
            TheDatePicker.Focus();
        }
        #endregion

        #region CreateChildControls
        /// <summary>
        /// Disply form Show Field Value.
        /// Edit and New forms. show the Drop Down List to pick the time and the date picker to pick the date
        /// </summary>
        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        protected override void CreateChildControls()
        {
            if (Field == null)
                return;

            base.CreateChildControls();

            if (ControlMode == SPControlMode.Display)
            {
                LabelDate = new Label();
                LabelDate.Text = this.ItemFieldValue.ToString();
                this.Controls.Add(LabelDate);
                return;
            }


            TheDatePicker = (DateTimeControl)TemplateContainer.FindControl("TheDatePicker");
            if (TheDatePicker.Equals(null))
            {
                throw new ArgumentException("Corrupt DateTimeByMinuteTemplate - Date Missing");
            }
            
            TheDatePicker.DateOnly = true;
            //TheDatePicker.LocaleId = Thread.CurrentThread.CurrentCulture.LCID;
            TheDatePicker.TabIndex = TabIndex;
            TheDatePicker.LocaleId = (int)base.ItemContext.RegionalSettings.LocaleId;
            TheDatePicker.TimeZoneID = base.ItemContext.RegionalSettings.TimeZone.ID;
            TheDatePicker.UseTimeZoneAdjustment = true;
            TheDatePicker.HijriAdjustment = base.ItemContext.RegionalSettings.AdjustHijriDays;
            TheDatePicker.HoursMode24 = base.ItemContext.RegionalSettings.Time24;
            TheDatePicker.FirstDayOfWeek = (int)base.ItemContext.RegionalSettings.FirstDayOfWeek;
            TheDatePicker.FirstWeekOfYear = base.ItemContext.RegionalSettings.FirstWeekOfYear;
            TheDatePicker.ShowWeekNumber = base.ItemContext.RegionalSettings.ShowWeeks;



            TheDatePicker.TabIndex = TabIndex;
            TheDatePicker.ToolTip = Field.Title + " Date";

            DropDownHH = (DropDownList)TemplateContainer.FindControl("DropDownHH");
            if (DropDownHH.Equals(null))
            {
                throw new ArgumentException("Corrupt DateTimeByMinuteTemplate - HH Missing");
            }
            DropDownHH.TabIndex = TabIndex;
            DropDownHH.CssClass = CssClass;
            DropDownHH.ToolTip = Field.Title + " Hour";

            DropDownMM = (DropDownList)TemplateContainer.FindControl("DropDownMM");

            if (DropDownMM.Equals(null))
            {
                throw new ArgumentException("Corrupt DateTimeByMinuteTemplate - MM Missing");
            }
            DropDownMM.TabIndex = TabIndex;
            DropDownMM.CssClass = CssClass;
            DropDownMM.ToolTip = Field.Title + " Minute";


            DropDownSS = (DropDownList)TemplateContainer.FindControl("DropDownSS");

            if (DropDownSS.Equals(null))
            {
                throw new ArgumentException("Corrupt DateTimeByMinuteTemplate - SS Missing");
            }
            DropDownSS.TabIndex = TabIndex;
            DropDownSS.CssClass = CssClass;
            DropDownSS.ToolTip = Field.Title + " Second";


            if (ControlMode == SPControlMode.New)
            {
                DropDownHH.Text = "00"; // Field.GetCustomProperty("DefaultHH").ToString();
                DropDownMM.Text = "00"; // Field.GetCustomProperty("DefaultMM").ToString();
                DropDownSS.Text = "00"; 
            }
        }
        #endregion

        #region Render
        //protected override void Render(HtmlTextWriter output)
        //{
            
            
        //    if (this.ControlMode == SPControlMode.Display)
        //    {
                
        //        LabelDate.RenderControl(output);
        //    }

        //}
        protected override void Render(HtmlTextWriter output)
        {
            if (this.ControlMode == SPControlMode.Display)
                LabelDate.RenderControl(output);
            else
                base.Render(output);
        }
        #endregion
    }
}

